#pragma once

#include <iostream>
#include <sys/socket.h>
#include <string>
#include <sys/types.h>
#include <cstring>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <functional>
#include <signal.h>
#include <unistd.h>
#include <sys/wait.h>
#include "Thread.hpp"
#include "BlockQueue.hpp"
#include "ThreadPool.hpp"
#include "Task.hpp"
namespace yui
{
    class TcpServer;
    class ThreadData
    {
        public:
        ThreadData(int sock,const std::string& ip,const uint16_t&port,TcpServer* ptr)
            :sock_(sock),clientip_(ip),clientPort_(port),current_(ptr)
            {}
        public:
        int sock_;
        std::string clientip_;
        uint16_t clientPort_;
        TcpServer* current_;
    };
    const uint16_t defaultPort = 8888;
    const int backlog = 32;
    using func_t = std::function<std::string(std::string)>;
    class TcpServer
    {
    public:
        TcpServer(func_t func, uint16_t port = defaultPort)
            : port_(port), quit_(false), func_(func)
        {
        }
        ~TcpServer()
        {
        }
        void InitServer()
        {
            listensock_ = socket(AF_INET, SOCK_STREAM, 0);
            if (listensock_ == -1)
            {
                perror("socket fail");
                exit(1);
            }
            std::cout << "Create ListenSocket Success" << listensock_ << std::endl;

            // 绑定ip port
            struct sockaddr_in local;
            bzero(&local, sizeof(local));
            local.sin_family = AF_INET;
            local.sin_addr.s_addr = INADDR_ANY;
            local.sin_port = htons(port_);
            if (bind(listensock_, (const sockaddr *)&local, sizeof(local)))
            {
                perror("bind fail");
                exit(1);
            }
            // 监听
            if (listen(listensock_, backlog) == -1)
            {
                perror("listen fail");
                exit(1);
            }
            std::cout << "listen success" << std::endl;
        }
        // 启动服务器
        void StartServer()
        {
            // signal(SIGCHLD,SIG_IGN);
            while (!quit_)
            {
                // 处理链接请求
                struct sockaddr_in client;
                socklen_t len = sizeof(client);
                int sock = accept(listensock_, (struct sockaddr *)&client, &len);
                if (sock == -1)
                {
                    perror("accept fail");
                    continue;
                }
                // 连接成功，获取客户信息
                std::string clientip = inet_ntoa(client.sin_addr);
                uint16_t clientport = ntohs(client.sin_port);
                std::cout << "Server accept " << clientip + "-" << clientport << " " << sock << " from " << listensock_ << " success!" << std::endl;
                // ThreadData* td = new ThreadData(sock,clientip,clientport,this);
                // pthread_t p;
                // pthread_create(&p,nullptr,Routine,td);
                yui::Task t(sock,clientip,clientport,std::bind(&yui::TcpServer::Service,this,std::placeholders::_1,std::placeholders::_2,std::placeholders::_3));
                yui::ThreadPool<yui::Task>::getInstance()->pushTask(t);
                //yui::ThreadPool<yui::Task>::getInstance()->start();
                

            }
        }
        /*static void* Routine(void* args)
        {
            pthread_detach(pthread_self());
            ThreadData* td = static_cast<ThreadData*>(args);
            td->current_->Service(td->sock_,td->clientip_,td->clientPort_);
            delete td;
        }/*/
        // 业务处理
        void Service(int sock, const std::string &clientip, const uint16_t &clientport)
        {
            char buff[1024];
            std::string who = clientip + "-" + std::to_string(clientport);
            while (true)
            {
                ssize_t n = read(sock, buff, sizeof(buff) - 1);
                if (n > 0)
                {
                    buff[n] = 0;
                    std::cout << "Server get:" << buff << " from" << who << std::endl;
                    std::string respond = func_(buff);
                    // 发送给服务器
                    write(sock, buff, strlen(buff));
                }
                else if (n == 0)
                {
                    std::cout << "Client " << who << " " << sock << "quit" << std::endl;
                    close(sock);
                    break;
                }
                else
                {
                    perror("read fail");
                    close(sock);
                    break;
                }
            }
        }

    private:
        int listensock_;
        uint16_t port_;
        bool quit_;
        func_t func_;
    };

}